#激光识别
import sensor, image, time
from machine import UART

#阈值
red = [(38, 100, 23, 127, -58, 66)]

roi = [67,36,175,181]

#找出返回色块列表中最大色块
def findMaxBlob(blobs):
    MaxSize = 0
    for blob in blobs:
            if blob[2]*blob[3] >= MaxSize:
                MaxSize = blob[2]*blob[3]
                MaxBlob = blob
    return MaxBlob

#数据打包
def outuart(x,y):#发送激光坐标
    global uart
    #发送数据
    uart.write('@')
    uart.write(str(x))
    uart.write(',')
    uart.write(str(y))
    uart.write(',')
    uart.write('\r\n')

# 初始化摄像头
sensor.reset()
sensor.set_pixformat(sensor.RGB565) # 设置图像色彩格式为RGB565格式
sensor.set_framesize(sensor.QVGA)  # 设置图像大小为160*120
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
sensor.set_auto_exposure(False,exposure_us = 135)
sensor.set_contrast(3)
sensor.set_saturation(3)
sensor.skip_frames(time = 20)       # 跳过帧

#uart初始化
uart = UART(2,115200)
uart.init(115200, bits=8, parity=None, stop=1)

#时钟初始化
clock = time.clock()

while(True):
    clock.tick()
    img = sensor.snapshot()
    blobs = img.find_blobs(red,pixels_threshold=0, area_threshold=0, x_stride = 1, y_stride = 1, roi = roi,merge=True,invert = 0)
    if(blobs):
        MaxBlob = findMaxBlob(blobs)
        img.draw_cross(MaxBlob.cx(),MaxBlob.cy())
        outuart(MaxBlob.cx(),MaxBlob.cy())
        print(MaxBlob.cx(),MaxBlob.cy())
        img.draw_rectangle(roi)

